# == Schema Information
# Schema version: 38
#
# Table name: topics
#
#  id           :integer(11)     not null, primary key
#  group_id     :integer(11)
#  user_id      :integer(11)
#  title        :string(255)
#  content      :text
#  content_html :text
#  sticky       :boolean(1)
#  created_at   :datetime
#  updated_at   :datetime
#  replied_at   :datetime
#  replied_by   :integer(11)
#  posts_count  :integer(11)     default(0)
#

class Topic < ActiveRecord::Base
  cattr_reader :per_page
  @@per_page = 20
  
  belongs_to :group
  belongs_to :user
  belongs_to :replied_by_user, :class_name => "User", :foreign_key => "replied_by"
  has_many :posts, :order => "created_at asc", :dependent => :delete_all
  
  validates_presence_of :title, :content
  
  format_attribute :content
  
  # before_save :content_with_formatting
  
  #after_save :update_group_after_save
    
  def editable_by?(user)
    user!=:false && (user.id == user_id || user.is_admin? || self.group.moderated_by?(user))
  end
  
  def self.newest
    self.find(:first, :order => "updated_at desc")
  end
  
  def self.archives
    date_func = "extract(year from created_at) as year,extract(month from created_at) as month"
    
    counts = Topic.find_by_sql(["select count(*) as count, #{date_func} from topics where created_at < ? group by year,month order by year asc,month asc",Time.now])
    
    sum = 0
    result = counts.map do |entry|
      sum += entry.count.to_i
      {
        :name => entry.year + "年" + entry.month + "月",
        :month => entry.month.to_i,
        :year => entry.year.to_i,
        :delta => entry.count,
        :sum => sum
      }
    end
    return result.reverse
  end
  
  protected
  def content_with_formatting
    self.content = auto_link(self.content) { |text| truncate(text, 50) }
    self.content = white_list(self.content)
  end

  
  private
  def update_group_after_save
=begin
    Group.find(:all).each do |group|
      group.topics_count = Topic.count(:conditions => {:group_id => group.id})
      group.save!
    end
=end
    group = self.group
    group.topics_count = Topic.count(:conditions => {:group_id => group.id})
    group.save!
  end  
  
end
